package com.cn.jinl.service;

import com.cn.jinl.api.*;
import com.cn.jinl.conf.Config;
import com.cn.jinl.dao.CheckLineMapper;
import com.cn.jinl.domain.*;
import com.cn.jinl.utils.CommonUtil;
import com.cn.jinl.utils.Constants;
import com.cn.jinl.utils.QueryForm;
import com.cn.jinl.utils.WordUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class CheckLineServiceImpl implements ICheckLineService {


    @Autowired
    private CheckLineMapper checkLineMapper;


    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IOnDutyPersonService onDutyPersonService;

    @Autowired
    private IOnDutyProductService onDutyProductService;

    @Autowired
    private ILineOtherService lineOtherService;

    @Autowired
    private IChenxingMachineService chenxingMachineService;

    @Autowired
    private ISterilizeService sterilizeService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private Config config;



    @Override
    public List<CheckLine> getHistoryCheckLineLists(QueryForm queryForm) throws Exception {
        int count = checkLineMapper.selectHistoryCheckLineCount(queryForm);
        if(count == 0){
            return Lists.newArrayList();
        }
        List<CheckLine> checkLines = checkLineMapper.selectHistoryCheckLines(queryForm);
        checkLines.get(0).setCount(count);
        return checkLines;
    }

    @Override
    public Map<String, Object> getCheckLineListMap(QueryForm queryForm) throws Exception {
        Map<String,String>dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        String whiteDay = dutyMap.get("whiteDay");
        String banZhang = onDutyPersonService.getOnDutyPersonByDutyAndWhite(dutyDay,whiteDay);

        //1 质检 2巡检
        String tabType = queryForm.getType();
        String processName = queryForm.getProcessName();
        String processCategory = queryForm.getProcessCategory();

        CheckLineExample example = new CheckLineExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andWhiteDayEqualTo(whiteDay).andDutyDayEqualTo(dutyDay).andTabTypeEqualTo(tabType);
        List<CheckLine> checkLines = checkLineMapper.selectByExample(example);
        example.setOrderByClause("create_time asc");
        Map<String,CheckLine> checkLineMap = Maps.newHashMap();
        for(CheckLine checkLine :checkLines){
            checkLineMap.put(checkLine.getDeviceCode(),checkLine);
        }
        queryForm.setWhiteDay(whiteDay);
        queryForm.setDutyDay(dutyDay);

        Map<String,String> deviceGradeMap = Maps.newHashMap();

        if(StringUtils.equals(processName,"包装")){
            if(StringUtils.equals(processCategory,"单多支")){
                queryForm.setProcessCategory("单支连排");
                Map<String,String> map1 = onDutyProductService.getOnDutyProductStatusMap(queryForm);
                queryForm.setProcessCategory("多支");
                Map<String,String> map2 = onDutyProductService.getOnDutyProductStatusMap(queryForm);
                int openNum = Integer.parseInt(map1.get("openNum"))+Integer.parseInt(map2.get("openNum"));
                deviceGradeMap.put("openNum",openNum+"");
                for(String key:map1.keySet()){
                    if(!StringUtils.equals("openNum",key)){
                        deviceGradeMap.put(key,map1.get(key));
                    }
                }
                for(String key:map2.keySet()){
                    if(!StringUtils.equals("openNum",key)){
                        deviceGradeMap.put(key,map2.get(key));
                    }
                }
            }else{
                deviceGradeMap = onDutyProductService.getOnDutyProductStatusMap(queryForm);
            }
        }else if(StringUtils.equals(processName,"挤塑直切")){
            deviceGradeMap = lineOtherService.getLineOtherStatusMap(queryForm);
        }else if(StringUtils.equals(processName,"成型")){
            deviceGradeMap = chenxingMachineService.getChenxingMachineStatusMaps();
        }
        boolean ds = false;
        if(StringUtils.equals(processCategory,"单多支")){
            processCategory = "";
            ds = true;
        }
        Map<String,List<String>> deviceMaps = deviceService.getDeviceByProcName(processName,processCategory);
        List<CheckLine> checkLineList = Lists.newArrayList();
        int totalCount = 0;
        for(String key :deviceMaps.keySet() ){
            if(ds && (!StringUtils.equals("单支连排",key)&& !StringUtils.equals("多支",key))){
                continue;
            }
            List<String> deviceCodes = deviceMaps.get(key);
            for(String code : deviceCodes){
                totalCount++;
                if(checkLineMap.containsKey(code)){
                    checkLineList.add(checkLineMap.get(code));
                }else{
                    CheckLine add = new CheckLine();
                    if(deviceGradeMap.containsKey(code)){
                        add.setGradeValue(deviceGradeMap.get(code));
                        add.setPlanName(deviceGradeMap.get(code+"#"));
                    }
                    add.setDeviceCode(code);
                    checkLineList.add(add);
                }
            }
        }
        String openNum = deviceGradeMap.get("openNum");

        Map<String,Object> resultMap = Maps.newHashMap();
        resultMap.put("checkLines",checkLineList);
        resultMap.put("dutyDay",dutyDay);
        resultMap.put("whiteDay",whiteDay);
        resultMap.put("banZhang",banZhang);
        resultMap.put("totalCount",totalCount);
        resultMap.put("openNum",openNum);
        resultMap.put("waiting",totalCount - Integer.parseInt(openNum));
        return resultMap;
    }

    @Override
    public String addCheckLine(CheckLine checkLine) throws Exception {
        Map<String, Object> resultMap = deviceService.getOnDutyDeviceInfoByCode(checkLine.getDeviceCode());
        String error = (String) resultMap.get("error");
        if(StringUtils.isNotEmpty(error)){
            return error;
        }
        Device device = (Device) resultMap.get("device");
        String processName = device.getProcessName();
        String itemTypeId = device.getProcessCategory();
        String procType = "";
        if (StringUtils.equals("U管成型", itemTypeId)) {
            procType = "5";
        } else if (StringUtils.equals("挤塑直切", processName)) {
            procType = "4";
        } else if (StringUtils.equals("包装", processName)) {
            if (StringUtils.equals("单支连排", itemTypeId) || StringUtils.equals("多支", itemTypeId)) {
                procType = "1";
            } else if (StringUtils.equals("U型", itemTypeId)) {
                procType = "2";
            } else if (StringUtils.equals("伸缩", itemTypeId)) {
                procType = "3";
            }
        }
        checkLine.setProcType(procType);
        Map<String, String> dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        String whiteDay = dutyMap.get("whiteDay");
//        CheckLineExample example = new CheckLineExample();
//        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS)
//                .andDeviceCodeEqualTo(checkLine.getDeviceCode()).andWhiteDayEqualTo(whiteDay).andDutyDayEqualTo(dutyDay).andTabTypeEqualTo(checkLine.getTabType());
//
//        List<CheckLine> checkLines = checkLineMapper.selectByExample(example);
//        if(!CollectionUtils.isEmpty(checkLines)){
//            return "线检已经存在，请刷新再试！";
//        }

        checkLine.setId(CommonUtil.generateRandomNum("checkLine-"));

        checkLine.setDutyDay(dutyDay);
        checkLine.setWhiteDay(whiteDay);
        int count = checkLineMapper.insertSelective(checkLine);
        return CommonUtil.outStr(count);
    }

    @Override
    public String addJSZZQCheckLine(CheckLine checkLine) throws Exception {
        Map<String,String>dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        String whiteDay = dutyMap.get("whiteDay");
        checkLine.setId(CommonUtil.generateRandomNum("checkLine-"));
        checkLine.setDutyDay(dutyDay);
        checkLine.setWhiteDay(whiteDay);
        int count = checkLineMapper.insertSelective(checkLine);
        if(count < 0){
            return "插入线检异常！";
        }
        Sterilize sterilize = new Sterilize();
        sterilize.setDeviceCode(checkLine.getDeviceCode());
//        sterilize.setDutyDay(dutyDay);
//        sterilize.setWhiteDay(whiteDay);
        sterilize.setSterilizeType("1");
        sterilize.setTabName("挤塑直切");
        sterilize.setSterilizeWater("75%酒精");
        sterilize.setSterilizeUserName(checkLine.getUserName());
        String resp = sterilizeService.addSterilize(sterilize);
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateCheckLine(CheckLine checkLine) throws Exception {
        CheckLineExample example = new CheckLineExample();
        example.createCriteria().andIdEqualTo(checkLine.getId());
        int count = checkLineMapper.updateByExampleSelective(checkLine, example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String addOrUpdateCheckLine(CheckLine checkLine) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        String checkTime = simpleDateFormat.format(new Date());
        checkLine.setCheckTime(checkTime);
        checkLine.setCheckCount(1);
        String resp = this.addCheckLine(checkLine);;
        return resp;
    }

    @Override
    public String exportCheckLineList(QueryForm queryForm) throws Exception {
        List<CheckLine> checkLines = checkLineMapper.selectAllHistoryCheckLines(queryForm);
        String path = request.getSession().getServletContext().getRealPath("/WEB-INF/classes/");
        Map<String,Object> maps = Maps.newHashMap();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String queryTime = simpleDateFormat.format(new Date());
        maps.put("userName",queryForm.getName()+" "+queryTime);
        String period = queryForm.getStartTime()+"至"+queryForm.getEndTime().split(" ")[0];
        maps.put("queryPeriod",period);
        maps.put("count",checkLines.size());

        Set<String> deviceSet = Sets.newHashSet();
        String queryCode = "";
        for(int i =0 ;i < checkLines.size(); i++){
            CheckLine checkLine = checkLines.get(i);
            checkLine.setIndex(i+1);
            if(StringUtils.isEmpty(checkLine.getUserName())){
                checkLine.setUserName("");
            }
            queryCode = checkLine.getDeviceCode();
            deviceSet.add(checkLine.getDeviceCode());
        }
        if(CollectionUtils.isEmpty(deviceSet)){
            return "设备查询异常";
        }
        String deviceCodes = String.join(",", deviceSet);
        maps.put("deviceCode",deviceCodes);
        Device device = deviceService.getDeviceInfoByCode(queryCode);
        if(null == device){
            return "设备查询异常";
        }
        for(CheckLine checkLine:checkLines){
            this.setObjectFieldsNotNull(checkLine);
        }
        maps.put("processName",device.getProcessName());
        maps.put("itemName",device.getProcessCategory());
        maps.put("xianjians",checkLines);

        String template = "other_check.ftl";
        if(StringUtils.equals(queryForm.getProcessCategory(),"伸缩")){
            template = "SS_check.ftl";
        }else if(StringUtils.equals(queryForm.getProcessCategory(),"U型")){
            template = "Uxing_check.ftl";
        }else if(StringUtils.equals(queryForm.getProcessCategory(),"U直")||StringUtils.equals(queryForm.getProcessCategory(),"伸直")||StringUtils.equals(queryForm.getProcessCategory(),"普直")){
            template = "USP.ftl";
        }else if(!CollectionUtils.isEmpty(queryForm.getProcessCategorys())){
            template = "dd_check.ftl";
        }
        String fileName = WordUtil.generateSterilizePdfPath(path,config.filePath,template,maps);
        return config.fileUrl+fileName;
    }

    public static void setObjectFieldsNotNull(CheckLine checkLine)throws Exception {
        Class<?> clazz = checkLine.getClass();
        Field[] fields = clazz.getDeclaredFields();
        List<String> attrs = Lists.newArrayList("deviceCode","gradeValue","planName","moKuan");
        for (Field field : fields) {
            field.setAccessible(true);
            String fieldName = field.getName();
            if(!attrs.contains(fieldName)&&fieldName.indexOf("value") < 0){
                continue;
            }
            Object fieldValue;
            try {
                fieldValue = field.get(checkLine);
            } catch (IllegalAccessException e) {
                fieldValue = null;
            }
            if(null == fieldValue){
                field.set(checkLine,"");
            }
        }
    }


    @Override
    public Map<String, Object> getCheckLineListMap(String deviceCode,String type) throws Exception {
        Map<String, Object> resultMap = deviceService.getOnDutyDeviceInfoByCode(deviceCode);
        String error = (String) resultMap.get("error");
        if(StringUtils.isNotEmpty(error)){
            return resultMap;
        }
        Device device = (Device) resultMap.get("device");
        Map<String, String> dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        String whiteDay = dutyMap.get("whiteDay");
        CheckLineExample example = new CheckLineExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andDeviceCodeEqualTo(deviceCode).andWhiteDayEqualTo(whiteDay).andDutyDayEqualTo(dutyDay).andTabTypeEqualTo(type);
        example.setOrderByClause("create_time desc");
        List<CheckLine> checkLines = checkLineMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(checkLines)) {
            CheckLine newLine = new CheckLine();
            newLine.setDeviceCode(deviceCode);
            newLine.setGradeValue(device.getGradeValue());
            newLine.setPlanName(device.getPlanName());
            resultMap.put("checkLine", new CheckLine());
        } else {
            resultMap.put("checkLine", checkLines.get(0));
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getAPICheckLineListMap(QueryForm queryForm) throws Exception {
        Map<String,String>dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        String whiteDay = dutyMap.get("whiteDay");

        String processName = queryForm.getProcessName();
        String processCategory = queryForm.getProcessCategory();
        String type = queryForm.getType();
        CheckLineExample example = new CheckLineExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andWhiteDayEqualTo(whiteDay).andDutyDayEqualTo(dutyDay).andTabTypeEqualTo(type);
        example.setOrderByClause("create_time desc");
        List<CheckLine> checkLines = checkLineMapper.selectByExample(example);

        Map<String,CheckLine> checkLineMap = Maps.newHashMap();
        for(CheckLine checkLine :checkLines){
            if(checkLineMap.containsKey(checkLine.getDeviceCode())){
                int checkCount =  checkLineMap.get(checkLine.getDeviceCode()).getCheckCount()+1;
                checkLineMap.get(checkLine.getDeviceCode()).setCheckCount(checkCount);
                continue;
            }
            checkLineMap.put(checkLine.getDeviceCode(),checkLine);
        }
        queryForm.setWhiteDay(whiteDay);
        queryForm.setDutyDay(dutyDay);

        Map<String,String> deviceGradeMap = Maps.newHashMap();

        if(StringUtils.equals(processName,"包装")){
            deviceGradeMap = onDutyProductService.getOnDutyProductStatusMap(queryForm);
        }else if(StringUtils.equals(processName,"挤塑直切")){
            deviceGradeMap = lineOtherService.getLineOtherStatusMap(queryForm);
        }else if(StringUtils.equals(processName,"成型")){
            deviceGradeMap = chenxingMachineService.getChenxingMachineStatusMaps();
        }

        Map<String,List<String>> deviceMaps = deviceService.getDeviceByProcName(processName,processCategory);
        List<CheckLine> checkLineList = Lists.newArrayList();
        int totalCount = 0;
        for(String key :deviceMaps.keySet() ){
            List<String> deviceCodes = deviceMaps.get(key);
            for(String code : deviceCodes){
                totalCount++;
                if(checkLineMap.containsKey(code)){
                    checkLineList.add(checkLineMap.get(code));
                }else{
                    CheckLine add = new CheckLine();
                    if(deviceGradeMap.containsKey(code)){
                        add.setGradeValue(deviceGradeMap.get(code));
                    }
                    add.setCheckTime("");
                    add.setCheckCount(0);
                    add.setDeviceCode(code);
                    checkLineList.add(add);
                }
            }
        }
        String openNum = deviceGradeMap.get("openNum");
        Map<String,Object> resultMap = Maps.newHashMap();
        resultMap.put("checkLines",checkLineList);
        resultMap.put("dutyDay",dutyDay);
        resultMap.put("whiteDay",whiteDay);
        resultMap.put("totalCount",totalCount);
        resultMap.put("openNum",openNum);
        resultMap.put("waiting",totalCount - Integer.parseInt(openNum));
        return resultMap;
    }

    @Override
    public List<Map<Object, Object>> getQualityAnalysisList(QueryForm queryForm) throws Exception {
        Map<String, String> processCategoryToJxs = new HashMap<>();
        processCategoryToJxs.put("U直", "8");
        processCategoryToJxs.put("伸直", "8");
        processCategoryToJxs.put("普直", "8");
        processCategoryToJxs.put("U管成型", "5");
        processCategoryToJxs.put("单多支", "12");
        processCategoryToJxs.put("伸缩", "13");
        processCategoryToJxs.put("U型", "11");
        List<Map<Object, Object>> resultList = new ArrayList<>();
        String[] processCategories = {"U直", "伸直", "普直", "U管成型", "单多支", "伸缩", "U型"};
        for (String category : processCategories) {
            HashMap<Object, Object> map = new HashMap<>();
            queryForm.setProcessCategory(category);
            int count = checkLineMapper.getQualityAnalysisCount(queryForm);
            map.put("gongxu", category);
            map.put("jxs", processCategoryToJxs.get(category));
            map.put("hgs", count);
            if (count==0){
                map.put("hgl", "");
            }else {
                map.put("hgl", "100%");
            }
            map.put("bhg", "0");
            resultList.add(map);
        }

        return resultList;
    }
}
